<template>
  <u-popup :show="show" mode="bottom" @close="onClose">
    <view class="multi-location-popup">
      <view class="popup-title-row">
        <view class="popup-title">选择库位（可多选）</view>
        <u-button class="select-all-btn" size="mini" type="primary" @click="toggleSelectAll">
          {{ isAllSelected ? '取消全选' : '全选' }}
        </u-button>
      </view>
      <view class="location-list-scroll">
        <u-checkbox-group v-model="innerSelectedIds" @update:modelValue="">
          <view v-for="loc in locationList" :key="loc.id" class="location-checkbox-row">
            <u-checkbox :label="loc.location_code" :name="loc.guid" />
          </view>
        </u-checkbox-group>
      </view>
      <view class="popup-actions">
        <u-button type="primary" @click="onConfirm">确定</u-button>
        <u-button @click="onClose">取消</u-button>
      </view>
    </view>
  </u-popup>
</template>

<script>
export default {
  name: 'LocationPop',
  props: {
    show: {
      type: Boolean,
      default: false
    },
    locationList: {
      type: Array,
      default: () => []
    },
    selectedIds: {
      type: Array,
      default: () => []
    }
  },
  emits: ['update:show', 'confirm', 'close', 'update:selectedIds'],
  data() {
    return {
    }
  },
  watch: {
    show(val) {
      if (val) {
        this.innerSelectedIds = [...this.selectedIds]
      }
    }
  },
  computed: {
    innerSelectedIds:{
      get(){
        return this.selectedIds
      },
      set(val){
        this.$emit('update:selectedIds', val)
      }
    },
    isAllSelected() {
      return this.locationList.length > 0 && this.innerSelectedIds.length === this.locationList.length
    }
  },
  methods: {
    toggleSelectAll() {
      if (this.isAllSelected) {
        this.innerSelectedIds = []
      } else {
        this.innerSelectedIds = this.locationList.map(loc => loc.guid)
      }
      this.$emit('update:selectedIds', this.innerSelectedIds)
    },
    onConfirm() {
      this.$emit('confirm', this.innerSelectedIds)
      this.$emit('update:show', false)
    },
    onClose() {
      this.$emit('close')
      this.$emit('update:show', false)
    }
  }
}
</script>
<style lang="scss" scoped>
.multi-location-popup {
  padding: 32rpx 24rpx 24rpx 24rpx;
  background: #fff;
  border-radius: 24rpx 24rpx 0 0;
}

.popup-title-row {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 24rpx;
}

.popup-title {
  font-size: 28rpx;
  font-weight: bold;
  text-align: center;
}

.select-all-btn {
  margin-left: 24rpx;
}

.location-list-scroll {
  max-height: 400rpx;
  overflow-y: auto;
  margin-bottom: 24rpx;
}

.location-list-scroll .u-checkbox-group {
  display: flex;
  flex-wrap: wrap;
}

.location-checkbox-row {
  display: flex;
  align-items: center;
  margin-bottom: 18rpx;
  width: 100%;
}

.popup-actions {
  display: flex;
  justify-content: space-between;
  margin-top: 32rpx;
  gap: 24rpx;
}
</style>